<?php

/**
 * 采购需求列表
 * QiuXiangCheng
 * Date 2016/07/22
 */
class Purchase_IndexController extends Controller_NeedLogin {

	/**
	 * 特采申请MODEL
	 * @var Object
	 */
	private $purchaseModel;

	/**
	 * 特采需求MODEL
	 * @var Object
	 */
	private $specialDemand;

	/**
	 * 即将导入的excel的相对路径
	 * @var String
	 */
	private $excelPath;

	/**
	 * 异常报告
	 * @var String
	 */
	private $exception = '';

	private static $exceptions = '';

	/**
	 * 初始化
	 */
	public function init() {

		parent::init();
		$this->purchaseModel = new Purchase_Model_ProductCheck;
		$this->specialDemand = new Purchase_Model_SpecialDemand;
	}

	/**
	 * 特采申请列表
	 * @return null
	 */
	public function indexAction() {
		
		$get = $this->getRequest()->getParams();
		$pageData = [];
		$limit = $this->_PAGELIMITER($pageData);
		$params['page'] = !empty($get['page']) ? $get['page'] : 1;
		$handle = new Base_Model_Department;
		$depts = $handle->getDepartment();
		$pageAmount = Purchase_Model_ProductCheck::computSpecialDemandPageAmount($get);
		$purchase = $this->purchaseModel->getSpecialApplyList('*', $get, $limit['limit']);

		$defaultTableFiled = 'operate,pcode,pthumb,title,product_from,product_image,product_category,develop_website,apply_mark,apply_time,apply_user,platform,develop_time,develop_user,develop_mark,develop_status,promote_time,promote_user,promote_time_limit,promote_mark,promote_status,link_id,post,sale,click';
		$productTableFiled = isset($_COOKIE['productTableFiled_special']) && !empty($_COOKIE['productTableFiled_special']) ? $_COOKIE['productTableFiled_special'] : $defaultTableFiled;
		$productTableFiled = array_filter(explode(',', $productTableFiled));

		$this->smarty->assign('depts', $depts);
		$this->smarty->assign('params', json_encode($get));
		$this->smarty->assign('datefrom', date('Y-m-d 00:00', strtotime('-2 month')));
		$this->smarty->assign('time', date('Y-m-d 23:59', time()));
		$this->smarty->assign('stocking_type', $this->purchaseModel::$stocking_type);
		$this->smarty->assign('examine_status', $this->purchaseModel::$examine_status);
		$this->smarty->assign('examine_status_2', $this->purchaseModel::$examine_status_for_list);
		$this->smarty->assign('list', $purchase['list']);
		$this->smarty->assign('purchase_status', $this->purchaseModel::$purchase_status);
		$this->smarty->assign('page', @$this->page($pageAmount, $pageData['action']));
		$this->smarty->assign('auth', $this->currentLoginUser('auth'));
		$this->smarty->assign('examine_list', $purchase['examine_list']);
		$this->smarty->assign('warehouse', Base_Model_Warehouse::fetchWarehouseNameByCode());
		$this->smarty->assign('examine_type', Purchase_Model_ProductCheck::$_examine_type);
		$this->smarty->assign('productTableFiled', $productTableFiled);
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('specialdata_index.php');
	}

	/**
	 * 批量审核特采数据申请列表
	 * @return Json
	 */
	public function examinepurchasesAction() {

		$result = ['status' => 0];
		$param = $this->_request->getParams();
		if (!isset($param['checkitem'])) {
			$result['message'] = '请勾选需要操作的项目，对于已勾选但已经审核通过或已作废的单据，实际上将不会勾选！因此，请确保你勾选的项目是有效的。';
		} else {
			switch ($param['examine_type']) {
				// 一级审核/驳回
				case 2:
				case 4:
					if (!in_array(433, $this->_session->currentLoginUser['auth'])) {
						$this->_helper->json(['status'=>0,'message'=>'您没有一级审核/驳回的权限']);
					};
					break;
				// 二级审核/驳回
				case 3:
				case 5:
					if (!in_array(434, $this->_session->currentLoginUser['auth'])) {
						$this->_helper->json(['status'=>0,'message'=>'您没有二级审核/驳回的权限']);
					};
					break;
				// 三级审核/驳回
				case 6:
				case 7:
					if (!in_array(435, $this->_session->currentLoginUser['auth'])) {
						$this->_helper->json(['status'=>0,'message'=>'您没有三级审核/驳回的权限']);
					};
					break;
				// 批量作废
				case 8:
					if (!in_array(432, $this->_session->currentLoginUser['auth'])) {
						$this->_helper->json(['status'=>0,'message'=>'您没有批量作废的权限']);
					};
					break;
			}
			// 取得真实的审核状态
			$param['user_id'] = $this->currentLoginUser('user_id');
			$param['user_name'] = $this->currentLoginUser('user_name');
			$param['examine_reason'] = isset($param['examine_reason']) ? $param['examine_reason'] : '';
			$statics = $this->purchaseModel->ExamineSpecialData($param);
			if ($statics['status'] == 1) {
				$result['message'] = '操作完成！';
				$result['status'] = 1;
			} else if ($statics['status'] == 1009) {
				$result['message'] = '异常：' . $statics['message'];
			} else {
				$result['message'] = '单据不符合审核/驳回条件';
			}
		}
		$this->renderJson($result);
	}

	/**
	 * 增加特采数据页面
	 */
	public function addAction() {
		// 下发平台虚拟仓数据
		$this->smarty->assign('warehouse_platform', $this->specialDemand->getWarehouseOfPlatform());
		$this->smarty->assign('depts', $this->getwarehouse());
		$this->smarty->display('specialdata_add.php');
	}

	/**
	 * 增加特采数据
	 */
	public function doaddAction() {

		$demand_fetched = 0; // 是否已经成为需求
		$post = $this->_request->getParams();
		$result = ['status' => 0, 'message' => Helper_Lang::$conf['Err1008']];
		Helper_Array::filterModels($post);
		$post['apply_user'] = $this->_session->user_name;
		//$post['remark'] = $post['apply_user'] . ' 申请' . $post['apply_num'] . '个, ' . date('Y-m-d H:i:s', time());
		//$post['remark'] = ltrim($post['remark']);
		$post['create_time'] = $post['update_time'] = date('Y-m-d H:i:s', time());
		$post['purchase_status'] = 0;
		// 验证数据完整性
		$this->check_special_data($post);
		// 根据当前添加的特采判断审核类型
		if ($post['platform_code'] == '') {
			$post['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($post['warehouse_code']);
		} else {
			$post['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($post['platform_code']);
		}
		/**
		 * 如果通过搜索仓库得到该仓库需审核的等级为1 则说明不需要审核 应该直接通过
		 * 在通过时 修改三个字段
		 */
		if ($post['examine_level'] == 1) {
			$story = new Application_Model_Story;
			$r = $story->addSpecialStory($post['goods_sn'], $post['warehouse_code'], $post['apply_num'], trim($post['platform_code'], '-'));
			if (!$r) {
				$result['message'] = '失败：' . $story->getErrorMsg();
				$this->_helper->json($result);
				return false;
			}
			$post['examine_status'] = 7;
			$post['purchase_status'] = 2;
			$post['billType'] = 1;
		}
		$purchase = new Purchase_Model_ProductCheck;
		if ($purchase->add($post)) {
			$result['status'] = 1;
			$result['message'] = Helper_Lang::$conf['Suc1001'];
		}
		$this->_helper->json($result);
	}

	/**
	 * 添加特采验证
	 */
	private function check_special_data($post) {
		$result = ['status' => 0, 'message' => Helper_Lang::$conf['Err1008']];
		// 仓库
		if ($post['warehouse_id'] == '') {
			$result['message'] = '仓库为必填项...';
			$this->_helper->json($result);
		}
		$productHandle = new Application_Model_Product;
		// 海淘分类id集合
		$cids = $productHandle->fetchCateIdsByCateId(2389);
		$product = $productHandle->getProduct($post['goods_sn']);
		if (in_array($product[0]['catalog_id'], $cids)) {
			if ($post['platform_code'] == '') {
				$result['message'] = '海淘分类平台仓为必填项...';
				$this->_helper->json($result);
			}
		}
		// 最小起定量
		$min_order = $this->minOrder($post['goods_sn']);
		if ($min_order && $min_order > $post['apply_num']) {
			$result['message'] = '备货数量不能小于最小起定量';
			$this->_helper->json($result);
		}
		// 最大备货量
		$productWarehouseStockModel = new Application_Model_ProductWarehouseStock();
		$productStockInfo = $productWarehouseStockModel->getOne($post['goods_sn'], $post['platform_code'] ? $post['platform_code'] : $post['warehouse_code']);
		$max_store = $this->maxStore($post['goods_sn'], $post['warehouse_code'], $post['platform_code'], $productStockInfo, $post['stocking_type']);
		if (isset($max_store['max_store']) && $max_store['max_store'] < $post['apply_num']) {
			$warehouseModel = new Application_Model_Warehouse();
			$result['message'] = "您添加的数量已超过最大备货量，无法添加！SKU：【{$post['goods_sn']}】，【{$warehouseModel->getName($post['platform_code'] ? $post['platform_code'] : $post['warehouse_code'])}】仓库";
			if ($productStockInfo) {
				if ($productStockInfo['stock_order_nums']) {
					$result['message'] .= "，订货数量：{$productStockInfo['stock_order_nums']}";
				}
				if ($productStockInfo['stock_on_way']) {
					$result['message'] .= "，在途库存：{$productStockInfo['stock_on_way']}";
				}
				if ($productStockInfo['stock_can_allot']) {
					$result['message'] .= "，可配库存：{$productStockInfo['stock_can_allot']}";
				}
			}
			if ($max_store['total']) {
				$result['message'] .= "，总采购需求：{$max_store['total']}";
			}
			$result['message'] .= " ，您最多只能添加：{$max_store['max_store']}";
			$this->_helper->json($result);
		}
		// 产品分类判断
		$product_info = $productHandle->getProduct($post['goods_sn'], 'catalog_id');
		if (!in_array($product_info[0]['catalog_id'], Application_Model_User::getCategory())) {
			$result['message'] = '您不具有该产品的分类权限，无法添加！';
			$this->_helper->json($result);
		}
		// 仓库判断
		if (!in_array($post['warehouse_code'], Application_Model_User::getWarehouse())) {
			$result['message'] = '您不具有该仓库的权限，无法添加！';
			$this->_helper->json($result);
		}
	}

	/**
	 * 获取商品的最小起定量
	 */
	private function minOrder($goodsSn) {
		$product_purchase_info = new Application_Model_ProductPurchaseInfo();
		$minOrder = $product_purchase_info->getOne($goodsSn);
		return intval($minOrder['min_order']);
	}
	/**
	 * 计算商品的最大备货量
	 */
	private function maxStore($goodsSn, $warehouse, $platform_code, $productStockInfo, $stocking_type) {
		if ($stocking_type != 1) {
			return [];
		}
		// 产品销量模型
		$productSalesModel = new Application_Model_ProductSales();
		// 存在平台仓则替换
		$tempware = $warehouse;
		if ($platform_code) {
			$warehouse = $platform_code;
		}
		$productSalesInfo= $productSalesModel->getOne($goodsSn, $warehouse);
		$fifteenDayBackupSales = $productSalesInfo['sale_15']??0;
		$sevenDayBackupSales = $productSalesInfo['sale_7']??0;
		$sevenDayRealSales = $productSalesInfo['real_sale_7']??0;

		$fifteenDayBackupSalesMean = $fifteenDayBackupSales / 15;
		$sevenDayBackupSalesMean = $sevenDayBackupSales / 7;
		$sevenDayRealSalesMean = $sevenDayRealSales / 7;

		// 分母为零
		if ($fifteenDayBackupSalesMean == 0) {
			$rate = 0.5;
		} else {
			$_7DaySalesDivide15DaySales = $sevenDayBackupSalesMean / $fifteenDayBackupSalesMean;
			$rate = $_7DaySalesDivide15DaySales;
			if (min(0.5, $_7DaySalesDivide15DaySales) == $_7DaySalesDivide15DaySales) {
				$rate = 0.5;
			} elseif (max(1.5, $_7DaySalesDivide15DaySales) == $_7DaySalesDivide15DaySales) {
				$rate = 1.5;
			}
		}
		// 一个商品备货量总和最大值
		$backupAmountLimit = ((0.4 * $fifteenDayBackupSalesMean + 0.6 * $sevenDayBackupSalesMean) * 2 * $rate * 30) + ($sevenDayRealSalesMean * 3);
		$backupAmountLimit = round($backupAmountLimit, 2);
		// 商品现在的可用库存
		$productStock = 0;
		if ($productStockInfo) {
			$productStock = $productStockInfo['stock_can_allot'] + $productStockInfo['stock_on_way'] + $productStockInfo['stock_order_nums'];
		}
		// 需求BC求和
		$story = new Application_Model_Story();
		if ($platform_code) {
			$story_info = $story->get($goodsSn, '', $platform_code);
		} else {
			$story_info = $story->get($goodsSn, $tempware, $platform_code);
		}
		// b和c需求产生的备货量
		$b_cStoryBackupQuantity = 0;
		$story_info_total = 0;
		foreach ($story_info as $s) {
			$b_cStoryBackupQuantity += ($s['b_story_quantity'] + $s['c_story_quantity']);
			$story_info_total += ($s['a_story_quantity'] + $s['b_story_quantity'] + $s['c_story_quantity']);
		}
		// 产品库存模型
		$warehouseProductModel = new Application_Model_WarehouseProduct();
		if (($productStock == 0 && $sevenDayBackupSalesMean == 0) || $warehouseProductModel->isNewProduct($goodsSn, $warehouse)) {
			return [];
		} else {
			return ['max_store' => $backupAmountLimit - $productStock - $b_cStoryBackupQuantity, 'total' => $story_info_total];
		}
	}
	// 计算商品的存销比
	private function get_stock_sale($goodsSn, $warehouse_code) {
		return Purchase_Model_ProductCheck::getPropertionForSaving($goodsSn, $warehouse_code);
	}
	/**
	 * 特采申请修改页面
	 * @return NULL
	 */
	public function editAction() {

		$special = new Purchase_Model_ProductCheck;
		$data = $special->getDatasByIDs([$this->getRequest()->getParam('id')], '*');
		if (count($data) == 0) {
			die('没找到这条数据...');
		}
		$this->smarty->assign('warehouse_platform', $this->specialDemand->getWarehouseOfPlatform());
		$this->smarty->assign('warehouses', $this->getwarehouse());
		$this->smarty->assign('data', $data[0]);
		$this->smarty->display('specialdata_edit.php');
	}

	/**
	 * 修改特采申请列表
	 * @return JSON
	 */
	public function doeditAction() {
		$result = ['status' => 0, 'message' => '未作修改！'];
		$post = $this->getRequest()->getParams();
		Helper_Array::filterModels($post);
		$id = array_shift($post);
		if (!isset($post['platform_code'])) {
			$post['platform_code'] = '';
		}
		//数据完整性验证
		$this->check_special_data($post);
		// 根据当前添加的特采
		if ($post['platform_code'] == '') {
			$post['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($post['warehouse_code']);
		} else {
			$post['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($post['platform_code']);
		}
		$post['update_time'] = date('Y-m-d H:i:s', time());
		if ($this->purchaseModel->updateSpecialData($post, $id)) {
			$result['status'] = 1;
			$result['message'] = Helper_Lang::$conf['Suc1002'];
		}
		$this->_helper->json($result);
	}
	/**
	 * 用于AJAX联动类别搜索插件
	 */
	public function getwarehouse() {

		$warehouseModel = new Base_Model_Warehouse;
		$wares = $warehouseModel->getWarehouseFilterFields('id, warehouse_name, warehouse_code');
		if (count($wares) == 0) {
			return false;
		}
		foreach ($wares as $k => $v) {
			$realGetWares[$v['id']] = $v;
		}
		unset($wares);
		return $realGetWares;
	}

	/**
	 * 提交之前做的验证 判断是否存在该SKU
	 * @return Json
	 */
	public function beforeaddAction() {

		$post = $this->_request->getParams();
		$product = new Application_Model_Product;
		$temp = $product->getProduct($post['goods_sn']);
		if (count($temp) > 0) {
			$result['pro'] = $temp[0];
			$result['haitao'] = 0;
			$cids = $product->fetchCateIdsByCateId(2389);
			if (in_array($result['pro']['catalog_id'], $cids)) {
				$result['haitao'] = 1;
			}
		} else {
			$result['pro'] = false;
		}
		$this->_helper->json($result);
	}

	/**
	 * 商品的特采数量大于20的时候调用此方法
	 * @return [type] [description]
	 */
	public function proportionAction() {

		$param = $this->_request->getParams();
		$this->_helper->json($this->purchaseModel->CheckShelfTime($param['goods_sn']));
	}

	/**
	 * 检查GET过来的东西
	 * @return Json
	 */
	public function checkpurchaseAction() {
		$param = $this->_request->getParams();
		$result['dept'] = Base_Model_Warehouse::getDeptIdByWarehouseCode($param['warehouse_code']);
		$result['pro'] = $this->get_stock_sale($param['goods_sn'], $param['warehouse_code']);
		$this->_helper->json($result);
	}

	public function delAction() {
		if (!in_array(431, $this->_session->currentLoginUser['auth'])) {
			$this->_helper->json(['status'=>0,'message'=>'您没有单个作废的权限']);
		}
		$get = $this->getRequest()->getParams();
		$date = date('Y-m-d', time());
		// 更新审核表
		$examine_data = [
			'psd_id' => $get['id'],
			'examine_type' => 8,
			'user_id' => $this->_session->user_id,
			'examine_username' => $this->_session->user_name,
			'examine_reason' => $get['examine_reason'],
			'examine_time' => $date,
			'cancel_date' => $date,
		];
		// 如果已经传输了PMS
		if ($get['type'] == 2) {
			$examine_data['cancel_date'] = date('Y-m-d', strtotime('+1 day'));
			$examine_data['examine_type'] = 9; // 次日作废
		}
		// 更新的特采表
		$examine_update = [
			'examine_status' => $examine_data['examine_type'],
			'update_time' => date('Y-m-d H:i:s', time()),
			'purchase_status' => 4,
			'examine_user' => $this->_session->user_name,
		];
		// 向审核表插入本次操作记录
		$insert = $this->purchaseModel->insertExamineData($examine_data);
		// 更新冗余字段
		$update = $this->purchaseModel->updateSpecialData($examine_update, $get['id']);
		echo $update;die();
	}

	/******************* 以下是特采需求相关的方法 ******************/

	/**
	 * 特采需求列表
	 * @return null
	 */
	public function specialdemandAction() {
		$get = $this->getRequest()->getParams();
		$pageData = [];
		$limit = $this->_PAGELIMITER($pageData);
		$params['page'] = !empty($get['page']) ? $get['page'] : 1;
		$params['page_size'] = !empty($get['page_size']) ? $get['page_size'] : $this->page_size;
		$dept = new Base_Model_Department;

		$sql = 'SELECT %fields%
				FROM p_special_purchase sp
				LEFT JOIN p_product p ON p.goods_sn = sp.goods_sn
				LEFT JOIN p_product_purchase ppp ON sp.goods_sn = ppp.goods_sn
				LEFT JOIN p_product_warehouse_stock pws ON sp.goods_sn = pws.goods_sn AND sp.warehouse_code = pws.warehouse_code %where%  GROUP BY sp.platform_code,sp.warehouse_code,sp.goods_sn';

		$db = Model_Db::getInstance();

		$where = ' WHERE sp.billType = 1 AND ';
		if (isset($get['examine_status']) && $get['examine_status'] != '-') {
			$where .= $db->quoteInto('AND bs.examine_status = ?', $get['examine_status']) . ' AND ';
		}

		if (isset($get['create_time'][0]) && !empty($get['create_time'][0])) {
			$where .= $db->quoteInto('sp.create_time >=?', $get['create_time'][0]) . ' AND ';
		}
		if (isset($get['create_time'][1]) && !empty($get['create_time'][1])) {
			$where .= $db->quoteInto('sp.create_time <= ?', $get['create_time'][1]) . ' AND ';
		}

		if (isset($get['latest_time'][0]) && !empty($get['latest_time'][0])) {
			$where .= $db->quoteInto('sp.latest_time >=?', $get['latest_time'][0]) . ' AND ';

		}
		if (isset($get['latest_time'][1]) && !empty($get['latest_time'][1])) {
			$where .= $db->quoteInto('sp.latest_time <=?', $get['latest_time'][1]) . ' AND ';
		}

		if (isset($get['search']) && !empty($get['search']) && $get['search_type'] != '-') {
			$searchFields = '';
			switch ($get['search_type']) {
			case 1:
				break;
			case 2:
				$searchFields = 'p.product_name';
				break;
			case 3:
				$searchFields = 'sp.apply_user';
				break;
			case 4:
				$searchFields = 'sp.remark';
				break;
			}
			if ($get['search_type'] == 1) {
				$goods_sn_arr = explode(',', $get['search']);
				$where .= $db->quoteInto('sp.goods_sn in (?) AND ', $goods_sn_arr);
			} else {
				$where .= $db->quoteInto("searchFields=%?%", $get['search']) . ' AND ';
			}
		}
		if (isset($get['warehouse_id']) && $get['warehouse_id'] != '-') {
			$where .= $db->quoteInto('sp.warehouse_id = ?', $get['warehouse_id']) . ' AND ';
		}
		$where .= $db->quoteInto(' p.catalog_id in (?) ', Application_Model_User::getCategory()) . ' AND ';
		$where .= '1=1';
		$sql = str_replace('%where%', $where, $sql);

		$countSql = str_replace('%fields%', 'sp.id', $sql);
		$pageAmount = $db->fetchOne('select count(id) from(' . $countSql . ") tmp ");
		$demand = [];
		if ($pageAmount) {
			$fields = 'sp.*,group_concat(sp.id) as ids, ppp.delivery_info, ppp.goods_resource_status, ppp.purchaser, pws.base_stock,pws.stock_on_way,
				pws.last_storage_time, p.product_status,p.original_img_url,p.thumb_url, SUM(sp.apply_num) sum_apply_num,
				SUM(sp.return_num) sum_return_num, SUM(sp.purchase_num) sum_purchase_num, max(sp.latest_time) as latest_time, max(sp.update_time) as create_time';
			$sql = str_replace('%fields%', $fields, $sql);
			$pageOffset = ($params['page'] - 1) * $this->page_size;
			$demand = $db->fetchAssoc($sql, $this->page_size, $pageOffset);
			//获取特采申请的备注信息
			$demandApplyIdsStr = array_column($demand, 'ids');
			$demandApplyIds = [];
			foreach ($demandApplyIdsStr as $_ids) {
				$demandApplyIds = array_merge($demandApplyIds, explode(',', $_ids));
			}
			$demandApplyRemark = $db->fetchAll('select * from p_special_purchase where ' . $db->quoteInto('id in(?)', $demandApplyIds));

			$ware_model = new Application_Model_Warehouse();
			while ($key = key($demand)) {
				// 如果有平台仓，可用库存和在途库存取平台仓的值
				if ($platform_code = $demand[$key]['platform_code']) {
					$warehouse = $ware_model->getWareHouseStock($platform_code, $demand[$key]['goods_sn']);
					$demand[$key]['base_stock'] = $warehouse['base_stock'];
					$demand[$key]['stock_on_way'] = $warehouse['stock_on_way'];
				}
				// 如果回货数量大于0
				if ($demand[$key]['return_num'] > 0) {
					$demand[$key]['return_log'] = Purchase_Model_SpecialDemand::fetchReturnAmount($demand[$key]['ids']);
				}

				//合并特采申请的备注信息
				$remarks = [];
				foreach ($demandApplyRemark as $values) {
					if ($demand[$key]['goods_sn'] == $values['goods_sn'] && $demand[$key]['warehouse_code'] == $values['warehouse_code'] && $demand[$key]['platform_code'] == $values['platform_code']) {
						$remarks[] = '申请人: ' . $values['apply_user'] . ';申请数量: ' . $values['apply_num'] . ';申请日期: ' . $values['create_time'] . ';采购状态：' . Purchase_Model_ProductCheck::$purchase_status[$values['purchase_status']];
						// 去除已失效的特采数量
						if ($values['purchase_status'] == 4) {
							$demand[$key]['sum_apply_num'] -= $values['apply_num'];
						}
					}
				}
				$demand[$key]['remark'] = $remarks;
				next($demand);
			}

		}

		$this->smarty->assign('datefrom', date('Y-m-d', strtotime('-60 day')));
		$this->smarty->assign('depts', $dept->getDepartment());
		$this->smarty->assign('product_status', Application_Model_Product::STATUS);
		$this->smarty->assign('stocking_type', Purchase_Model_ProductCheck::$stocking_type);
		$this->smarty->assign('examine_status', Purchase_Model_SpecialDemand::$examine_level);
		$this->smarty->assign('purchase_status', Purchase_Model_ProductCheck::$purchase_status);
		$this->smarty->assign('list', $demand);
		$this->smarty->assign('params', json_encode($this->_request->getParams()));
		$this->smarty->assign('warehouse', Base_Model_Warehouse::fetchWarehouseNameByCode());
		$this->smarty->assign('page', $this->page($pageAmount, $pageData['action']));
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('specialdemand_index.php');
	}

	/**
	 * 上传Excel表格页面
	 */
	public function uploadExcelAction() {

		if ($this->doUpload() === 1) {
			// 将EXCEL里的东西导入
			if ($this->excelHandle()) {
				if (empty(self::$exceptions)) {
					self::$exceptions = Helper_Lang::$conf['Suc1003'];
				}
			}
		}
		$this->smarty->assign('message', self::$exceptions);
		$this->smarty->display('upload_excel.php');
	}

	/**
	 * 处理上传的文件
	 * @return boolean
	 */
	private function doUpload() {

		$canBeAbleToUpload = ['.xls'];
		if (count($_FILES) == 0) {
			self::$exceptions = Helper_Lang::$conf['Err1009'];
			return 0;
		}
		if (!is_uploaded_file($_FILES['excel']['tmp_name'])) {
			self::$exceptions = Helper_Lang::$conf['Err1010'];
			return 0;
		}
		$tmp_name = $_FILES['excel']['name'];
		$fixType = substr($tmp_name, strpos($tmp_name, '.'));
		if (!in_array($fixType, $canBeAbleToUpload)) {
			self::$exceptions = Helper_Lang::$conf['Err1011'];
			return 0;
		}
		$public_path = str_replace('\\', '/', PUBLIC_PATH);
		if (!move_uploaded_file($_FILES['excel']['tmp_name'], $public_path . '/upload/excel' . $fixType)) {
			self::$exceptions = Helper_Lang::$conf['Err1012'];
			return 0;
		}
		// 保存上传后的文件路径
		$this->excelPath = 'upload/excel' . $fixType;
		return 1;
	}

	/**
	 * 读EXCEL表
	 * @return Array
	 */
	public function excelHandle() {

		$excelPath = '../library/PHPExcel/';
		require_once $excelPath . "PHPExcel.php";
		require_once $excelPath . "PHPExcel/IOFactory.php";
		require_once $excelPath . "PHPExcel/Writer/Excel5.php";
		// 根据路径取得Excel数据
		$excelArr = $this->readExcel($this->excelPath);
		// 合并成可插入的数据
		$dataArr = $this->mergeExcelArrBySelf($excelArr);
		// 通过读取本excel的数据进行导入
		if (!$this->specialDemand->loadExcel($dataArr)) {
			self::$exceptions .= Helper_Lang::$conf['Err1013'];
			return false;
		}
		return true;
	}

	/**
	 * 数组自主合并
	 * @param 数组
	 * @return Array
	 */
	private function mergeExcelArrBySelf($excelArr) {

		$warehouse = new Application_Model_Warehouse;
		$warehouse = $warehouse->getWareHouseInfoByWName('', 'warehouse_name, warehouse_code, id');
		$arr = [];
		$exception = '';
		$amountError = 0;
		// 将要替换的数组数据
		$fields = Purchase_Model_SpecialDemand::$fieldsFromExcel;
		array_shift($excelArr);
		$productHandle = new Application_Model_Product;
		// 海淘分类id集合
		$cids = $productHandle->fetchCateIdsByCateId(2389);
		// 产品库存模型
		$productWarehouseStockModel = new Application_Model_ProductWarehouseStock();
		// 需求模型
		$story = new Application_Model_Story;
		foreach ($excelArr as $k => $v) {
			if (intval($v[1]) == 0) {
				continue;
			}
			// 中间值
			$product_category = '';
			$productStockInfo = array();
			$warehouse_code = '';
			foreach ($v as $key => $values) {
				// SKU
				if ($key == 0) {
					$data = $productHandle->getProduct($values, 'shelf_time, product_name, edit_status, product_status, catalog_id');
					if ($data) {
						if ($data[0]['edit_status'] != 4 && $data[0]['edit_status'] != 8 && $data[0]['edit_status'] != 10) {
							$amountError++;
							self::$exceptions .= '· L' . ($k + 2) . '，未审核通过产品：' . $values . '<br />';
							continue 2;
						} else if ($data[0]['goods_resource_status'] == 3) {
							$amountError++;
							self::$exceptions .= '· L' . ($k + 2) . '，产品停产无法添加：' . $values . '<br />';
							continue 2;
						} else {
							$product_category = $data[0]['catalog_id'];
							$temp['product_name'] = $data[0]['product_name'];
						}
					} else {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，系统不存在该SKU：' . $values . '；<br />';
						continue 2;
					}
				}
				// 备货数量
				if ($key == 1) {
					$values = intval($values);
					$min_order = $this->minOrder($v[0]);
					if ($values <= 0) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，备货销量不合法而未导入成功，检查备货销量并确定已书写正确！<br />';
						continue 2;
					} else if ($min_order && $min_order > $values) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，备货数量不能小于最小起订量。<br />';
						continue 2;
					}
				}
				// 替换仓库名称为代码
				if ($key == 3) {
					if (!isset($warehouse[$values])) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，因找不到仓库名称而未导入成功，检查该仓库是否存在并确定已书写正确！<br />';
						continue 2;
					}
					$temp['warehouse_id'] = $warehouse[$values]['id'];
					$values = $warehouse[$values]['warehouse_code'];
					$warehouse_code = $values;
				}
				// 最迟回货时间限制
				if ($key == 4) {
					if (strtotime($values) < strtotime(date('Y-m-d'))) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，因最迟回货时间小于当前时间而未导入成功，检查最迟回货时间并确定已书写正确！<br />';
						continue 2;
					}
				}
				// 预估销售时间段(左)限制
				if ($key == 5) {
					if (strtotime($values) < strtotime(date('Y-m-d'))) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，因预估销售时间段(左)小于当前时间而未导入成功，检查预估销售时间段(左)并确定已书写正确！<br />';
						continue 2;
					}
				}
				// 预估销售时间段(右)限制
				if ($key == 6) {
					if (strtotime($values) < strtotime(date('Y-m-d')) || strtotime($values) < strtotime($v[5])) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，因预估销售时间段(右)小于当前时间或小于预估销售时间段(左)而未导入成功，检查预估销售时间段(右)并确定已书写正确！<br />';
						continue 2;
					}
				}
				// 预估总销量查询
				if ($key == 7) {
					if (intval($values) < intval($v[1])) {
						$amountError++;
						self::$exceptions .= '· L' . ($k + 2) . '，预估总销量小于备货数量而未导入成功，检查预估总销量并确定已书写正确！<br />';
						continue 2;
					}
				}
				// 替换备货类型为数字代号
				if ($key == 8) {
					$temp['stocking_type_char'] = $values;
					$values = array_search($values, Purchase_Model_ProductCheck::$stocking_type);
				}
				// 平台仓
				if ($key == 10) {
					if (in_array($product_category, $cids)) {
						$current_platform = '';
						$platforms = $this->specialDemand->getWarehouseOfPlatform();
						foreach ($platforms as $platform) {
							if ($platform['warehouse_name'] == $values) {
								$current_platform = $platform['warehouse_code'];
								break;
							}
						}
						if ($current_platform == '') {
							$amountError++;
							self::$exceptions .= '· L' . ($k + 2) . '，平台仓不存在而未导入成功，检查平台仓并确定已书写正确！<br />';
							continue 2;
						}
						$values = $current_platform;
						$warehouse_code = $values;
					}
				}
				$temp[$fields[$key]] = $values;
			}
			// 存销比
			// 如果备货销量大于20或者新品上架时间大于30
			if (intval($v[1]) > 20 || ((strtotime(date("Y-m-d")) - strtotime($data[0]['shelf_time'])) > 30 * 24 * 3600)) {
				$propertion = $this->get_stock_sale($v[0], $warehouse_code);
				if ($propertion > 3) {
					$amountError++;
					self::$exceptions .= '· L' . ($k + 2) . '，产品的存销比大于3，请手动添加该SKU：' . $v[0] . '<br />';
					continue;
				}
			}
			// 最大备货量
			$productStockInfo = $productWarehouseStockModel->getOne($v[0], $warehouse_code);
			$max_store = $this->maxStore($v[0], $warehouse_code, '', $productStockInfo, $temp['stocking_type']);
			if (isset($max_store['max_store']) && $max_store['max_store'] < intval($v[1])) {
				$amountError++;
				self::$exceptions .= '· L' . ($k + 2) . ',备货数量超过了最大备货量而未导入成功，检查备货数量并确定已书写正确！<br />';
				continue;
			}
			// 审核判断
			if ($temp['platform_code'] == '') {
				$temp['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($temp['warehouse_code']);
			} else {
				$temp['examine_level'] = Purchase_Model_SpecialDemand::confirmForChoiceExamineLevel($temp['platform_code']);
			}
			/**
			 * 如果通过搜索仓库得到该仓库需审核的等级为1 则说明不需要审核 应该直接通过
			 * 在通过时 修改三个字段
			 */
			if ($temp['examine_level'] == 1) {
				$r = $story->addSpecialStory($temp['goods_sn'], $temp['warehouse_code'], $temp['apply_num'], trim($temp['platform_code'], '-'));
				if (!$r) {
					$amountError++;
					self::$exceptions .= '· L' . ($k + 2) . ',' . $story->getErrorMsg() . '<br />';
					continue;
				}
				$temp['examine_status'] = 7;
				$temp['purchase_status'] = 2;
				$temp['billType'] = 1;
			}
			// 产品分类判断
			$product_info = $productHandle->getProduct($temp['goods_sn'], 'catalog_id');
			if (!in_array($product_info[0]['catalog_id'], Application_Model_User::getCategory())) {
				$amountError++;
				self::$exceptions .= '· L' . ($k + 2) . ',不具备该sku的分类权限。<br />';
				continue;
			}
			// 仓库判断
			if (!in_array($temp['warehouse_code'], Application_Model_User::getWarehouse())) {
				$amountError++;
				self::$exceptions .= '· L' . ($k + 2) . ',不具备该仓库的权限。<br />';
				continue;
			}
			// $temp['examine_status'] = 1;
			// $temp['purchase_status'] = 0;
			$temp['apply_user'] = $this->_session->user_name;
			$temp['update_time'] = $temp['create_time'] = date('Y-m-d H:i:s', time());
			$arr[] = $temp;
		}
		self::$exceptions .= '· ' . $amountError . '条数据导入失败！<br />';
		return $arr;
	}

	/**
	 * 读EXCEL表
	 * @param $excel文件地址
	 * @param 编码
	 * @return Array
	 */
	function readExcel($filename) {

		$extarr = explode(".", $filename);
		if ($extarr[1] == "xlsx") {
			$objReader = PHPExcel_IOFactory::createReader('Excel2007');
		} else {
			$objReader = PHPExcel_IOFactory::createReader('Excel5');
		}
		//$objReader = PHPExcel_IOFactory::createReader('Excel5');
		$objReader->setReadDataOnly(true);
		$objPHPExcel = $objReader->load($filename);
		$objWorksheet = $objPHPExcel->getActiveSheet();
		$highestRow = $objWorksheet->getHighestRow();
		$highestColumn = $objWorksheet->getHighestColumn();
		$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
		$excelData = array();
		for ($row = 1; $row <= $highestRow; $row++) {
			for ($col = 0; $col < $highestColumnIndex; $col++) {
				$excelData[$row][] = (string) $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
			}
		}
		return $excelData;
	}
}
